package com.th.campusmatchbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.th.campusmatchbackend.common.BaseResponse;
import com.th.campusmatchbackend.common.ErrorCode;
import com.th.campusmatchbackend.common.ResultUtils;
import com.th.campusmatchbackend.exception.BusinessException;
import com.th.campusmatchbackend.model.domain.Team;
import com.th.campusmatchbackend.model.domain.User;
import com.th.campusmatchbackend.model.domain.UserTeam;
import com.th.campusmatchbackend.model.dto.TeamQuery;
import com.th.campusmatchbackend.model.request.*;
import com.th.campusmatchbackend.model.vo.TeamUserVO;
import com.th.campusmatchbackend.service.TeamService;
import com.th.campusmatchbackend.service.UserService;
import com.th.campusmatchbackend.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/team")
@Slf4j
public class TeamController {

    @Resource
    private UserService userService;
    @Resource
    private TeamService teamService;
    @Resource
    private UserTeamService userTeamService;


    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request){
        if(teamAddRequest==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User logininUser = userService.getCurrentUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest,team);
        long teamId = teamService.addTeam(team, logininUser);
        return ResultUtils.success(teamId);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request){
        if(deleteRequest == null||deleteRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        User longinUser = userService.getCurrentUser(request);
        boolean result = teamService.deleteTeam(id, longinUser);
        if(!result){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"删除失败");
        }
        return ResultUtils.success(true);
    }


    @PostMapping("/update")
    public  BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request){
        if(teamUpdateRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getCurrentUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest,loginUser);
        if(!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失败");
        }
        return ResultUtils.success(true);
    }

    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(long id){
        if(id<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Team team = teamService.getById(id);
        if(team==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(team);
    }

    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeams(TeamQuery teamQuery,HttpServletRequest request){
        if(teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        //1.查询队伍列表
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery,isAdmin);
        //根据查询条件查出的所有队伍的ID集合
        List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());

        //设置是否加入队伍
        isJoinTeam(request, teamList, teamIdList);
        //查询已加入队伍的人数
        QueryHasJoinNum(teamList, teamIdList);



        return ResultUtils.success(teamList);

    }


    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listPageTeams(TeamQuery teamQuery){
        if(teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team  =new Team();
        BeanUtils.copyProperties(teamQuery,team);
        Page<Team> page  = new Page<>(teamQuery.getPageNum(),teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper  = new QueryWrapper<>(team);
        Page<Team> resultPage = teamService.page(page,queryWrapper);

        return ResultUtils.success(resultPage);

    }

    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest,HttpServletRequest request){
        if(teamJoinRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getCurrentUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        return ResultUtils.success(result);
    }

    @PostMapping("/quit")
    public  BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest,HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getCurrentUser(request);

        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);

        return  ResultUtils.success(result);

    }
    /**
     * 获取我创建的队伍
     *
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getCurrentUser(request);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVO> teamList = teamService.listMyCreate(teamQuery);
        List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());
        //设置是否加入队伍
        isJoinTeam(request, teamList, teamIdList);
        //查询已加入队伍的人数
        QueryHasJoinNum(teamList, teamIdList);


        return ResultUtils.success(teamList);


    }
    /**
     * 获取我加入的队伍(包含创建人也算加入队伍)
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/join")
    public BaseResponse<List<TeamUserVO>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //User loginUser = userService.getCurrentUser(request);
        //teamQuery.setUserId(loginUser.getId());
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        //获取所有我创建的以及我加入的队伍
        queryWrapper.eq("userId", teamQuery.getUserId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);

        // 取出不重复的队伍 id
        // teamId userId
        Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        //UserTeam表中所有包含我的Id的队伍的Id
        List<Long> idList = new ArrayList<>(listMap.keySet());
        if(idList.size() == 0){
            return ResultUtils.success(new ArrayList<TeamUserVO>());
        }
        teamQuery.setIdList(idList);

        //根据这些队伍Id，查出队伍信息以及关联的创建者信息
        List<TeamUserVO> teamList = teamService.listMyJoinTeams(teamQuery);

        List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());

        teamList.forEach(team ->{
            boolean hasJoin = idList.contains(team.getId());
            team.setHasJoin(hasJoin);
        });
        //查询已加入队伍的人数
        QueryHasJoinNum(teamList, teamIdList);


        return ResultUtils.success(teamList);
    }


    private void isJoinTeam(HttpServletRequest request, List<TeamUserVO> teamList, List<Long> teamIdList) {
        //2.判断当前用户是==否已加入队伍==
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try{
            User loginUser = userService.getCurrentUser(request);
            //包含该用户的所有队伍
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            //位于查询条件下的所有队伍
            userTeamQueryWrapper.in("teamId", teamIdList);
            //查出这些队伍
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            //已加入的 队伍id 集合
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.forEach(team ->{
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        }catch(Exception e){}
    }

    private void QueryHasJoinNum(List<TeamUserVO> teamList, List<Long> teamIdList) {
        //使用try-catch的原因是查询数据库是可能会造成运行时异常
        //3、查询已加入队伍的人数
        try{
            QueryWrapper<UserTeam> userTeamJoinQueryWrapper  = new QueryWrapper<>();
            userTeamJoinQueryWrapper.in("teamId",teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
            //假如查出5条数据
            //userId    TeamId
            //18        42
            //3         42
            //19        44
            //18        45
            //19        45
            //清洗数据
            //队伍id => 加入这个队伍的用户列表
            Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
            teamList.forEach(team ->
                    team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(),new ArrayList<>()).size()));
        }catch (Exception e){}
    }


    /**
     * 查询队伍详细信息
     * @param teamQuery
     * @return
     */
    @GetMapping("/queryTeamInfo")
    public BaseResponse<TeamUserVO> queryTeamInfo(TeamQuery teamQuery,HttpServletRequest request){
     if(teamQuery == null){
         throw  new BusinessException(ErrorCode.PARAMS_ERROR);
     }

     TeamUserVO teamInfo = teamService.getTeamInfo(teamQuery,request);



     return ResultUtils.success(teamInfo);

    }



}
